﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.BillTrack;
using Kingdee.BOS.BusinessEntity.BusinessFlow;
using Kingdee.BOS.BusinessEntity.Login;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.ServiceHelper.HealthCenter;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.CN.App.ServicePlugIn.RecPayPurpose;
using LiMinCRMPlugin.InterfaceDocking;
using Microsoft.SqlServer.Server;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using static LiMinCRMPlugin.InterfaceDocking.ReceivableMode;

namespace LiMinCRMPlugin
{
    // <summary>
    /// 自动根据生产月度计划更新销售订单预计发货日期及推送CRM1
    /// </summary>
    /// <remarks>
    /// 功能：自动根据生产月度计划更新销售订单预计发货日期及推送CRM
    /// 创建人：mey
    /// 创建日期：2024年4月9日
    /// </remarks>
    [Description("自动根据生产月度计划更新销售订单预计发货日期及推送CRM")]
    [Kingdee.BOS.Util.HotUpdate]
    public class DeliveryDateUpdatePlan : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {


            int SaveDay = 30; //预计可发量保留天数

            //查询所有组织机构进行循环

            //首先判断当日是否存在单据头数据，如果存在直接插入单据体，不存在，先插入单据头
            string sql_org = @"/*dialect*/  select * from T_ORG_Organizations where forgid in(SELECT [FID]  FROM [AIS20240514124535].[dbo].[CRM_V_VAOrganizations]) ";//增加测试forgid  and  forgid=100084
            DataTable dt_org = DBUtils.ExecuteDataSet(ctx, sql_org).Tables[0];
            if (dt_org != null && dt_org.Rows.Count > 0)
            {
                for (int orgAdd = 0; orgAdd < dt_org.Rows.Count; orgAdd++)
                {
                    string forgid = dt_org.Rows[orgAdd]["FOrgID"].ToString();

                    GetPreRecorded(forgid, ctx, SaveDay);//预计入
                    OutboundQuantity(ctx, forgid, SaveDay);//预计出
                    GetAvailableQuantity(ctx, forgid, SaveDay); //预计可发量

                    if (1 == 1)
                    {

                        #region 循环修改销售订单的预计发货日期

                        //销售订单
                        string sql_SO = string.Format(@"/*dialect*/   select b.FENTRYID,b.FStockOrgId,F_QUQY_MATERIAL,FCANOUTQTY SaleQty,F_DEV_CRMEntryId,FBillNo,FMTONO  from T_SAL_ORDER a 
		inner join T_SAL_ORDERENTRY b on a.FID=b.FID
		inner join T_SAL_ORDERENTRYDELIPLAN c on b.FENTRYID=c.FENTRYID
        inner join T_SAL_ORDERENTRY_R d on b.fentryid=d.fentryid
		where FDOCUMENTSTATUS='C' and FCloseStatus='A' and FRemainOutQty>0 and b.FStockOrgId='" + forgid + "' and F_QUQY_MATERIAL<>0" +  // and FMaterialId=500978 
            " order by FDeliveryDate");
                        DataTable dt_SO = DBUtils.ExecuteDataSet(ctx, sql_SO).Tables[0];

                        if (dt_SO.Rows.Count > 0)
                        {
                            foreach (DataRow SO in dt_SO.Rows)
                            {
                                int SaleOrFE = 0;//声明变量存储临时数据  ERP明细内码
                                int StockOrgId = 0;//库存组织           ERP库存组织
                                int MaterialId = 0; //物料唯一内码       

                                decimal SaleQty = 0; //销售订单数量(剩余未通知数量（基本）)
                                string CRMEntryId = ""; //CRM内码
                                string FBillNo = SO["FBillNo"].ToString();
                                SaleOrFE = Convert.ToInt32(SO["FENTRYID"]);
                                StockOrgId = Convert.ToInt32(SO["FStockOrgId"]);
                                MaterialId = Convert.ToInt32(SO["F_QUQY_MATERIAL"]);
                                SaleQty = Convert.ToDecimal(SO["SaleQty"]);
                               
                                CRMEntryId = Convert.ToString(SO["F_DEV_CRMEntryId"]);//

                                string sql_A = string.Format("/*dialect*/select fentryid,F_RDLV_DateE,F_RDLV_SaleOrderQty,(F_QLTK_Inventory+F_QLTK_PreRecorded-F_QLTK_OutboundQuantity+F_QLTK_DailyForecast)+" + SaleQty + " AvailableQty from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid and F_RDLV_AvailableQty+" + SaleQty + ">F_RDLV_SaleOrderQty and CONVERT(varchar(100), F_RDLV_Date, 23)= '" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_RDLV_Materal='" + MaterialId + "' and F_RDLV_OrgIdE='" + StockOrgId + "' and F_QLTK_Tracking= '" + SO["FMTONO"].ToString() + "'  order by F_RDLV_DateE");
                                DataTable dt_A = DBUtils.ExecuteDataSet(ctx, sql_A).Tables[0];
                                if (dt_A != null && dt_A.Rows.Count > 0)
                                {
                                    foreach (DataRow item in dt_A.Rows)
                                    {


                                        Decimal AvailableQty = Convert.ToDecimal(item["AvailableQty"]);//预计可发量
                                        Decimal SaleOrderQty = Convert.ToDecimal(item["F_RDLV_SaleOrderQty"]);//销售订单已扣减
                                        string AvailableFentryid = item["Fentryid"].ToString();

                                        string AntiShipmentDate = item["F_RDLV_DateE"].ToString(); //库存日期
                                        if ((AvailableQty - SaleOrderQty) >= SaleQty)//本次够扣减
                                        {
                                            string sql_UP = string.Format(@"/*dialect*/update T_SAL_ORDERENTRY set F_RDLV_AntiShipmentDate='{0}' where FENTRYID='{1}'", AntiShipmentDate, SaleOrFE);
                                            DBUtils.Execute(ctx, sql_UP);

                                            //扣减
                                            string sql_uA = string.Format(@"/*dialect*/update RDLV_t_AvailableQuantityE set F_RDLV_SaleOrderQty='{0}' where FENTRYID='{1}'", SaleOrderQty + SaleQty, AvailableFentryid);
                                            DBUtils.Execute(ctx, sql_uA);
                                            //推送CRM
                                            if (1 == 1)
                                            {


                                                if (CRMEntryId != "")
                                                {
                                                    mainTableList mainTable = new mainTableList();
                                                    mainTable.ddbh = FBillNo;
                                                    List<detailList> detailList = new List<detailList>();//明细数据组

                                                    #region 销售订单detail数组
                                                    operate operate = new operate();
                                                    operate.action = "SaveOrUpdate";

                                                    dataList dataList = new dataList();
                                                    dataList.erpyjfhrq = AntiShipmentDate;
                                                    dataList.id = CRMEntryId;

                                                    detailList detailList1 = new detailList();
                                                    detailList1.operate = operate;
                                                    detailList1.data = dataList;
                                                    detailList.Add(detailList1);
                                                    #endregion
                                                    Return resultAdd = CRMUpdateSalesOrder(ctx, mainTable, detailList);
                                                    if (resultAdd.status == "1")
                                                    {
                                                        //成功了不写日志。太繁琐
                                                    }
                                                    else
                                                    {
                                                        #region 销售订单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                                        Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                                        interfaceLog.FBILLNO = FBillNo;
                                                        interfaceLog.FBILLID = "";
                                                        interfaceLog.FDATE = System.DateTime.Now;
                                                        interfaceLog.FINTERNAME = "更新销售订单";
                                                        interfaceLog.FInvokeType = "自动执行计划更新预计发货日期";
                                                        interfaceLog.Ftoken = "";
                                                        interfaceLog.FSTATUS = "失败";
                                                        interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                                        interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                                                        interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"kd-jxy\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                                        interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                                                        string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                                        List<string> sqlList = new List<string>();
                                                        if (!string.IsNullOrEmpty(LogSql))
                                                        {
                                                            sqlList.Add(LogSql);
                                                        }
                                                        //更新单据

                                                        //DBServiceHelper.ExecuteBatch(ctx, sqlList);
                                                        #endregion
                                                    }
                                                }

                                            }
                                            break;
                                        }
                                        else//本次不够扣减
                                        {
                                            //扣减  扣减完接着循环
                                            string sql_uA = string.Format(@"/*dialect*/update RDLV_t_AvailableQuantityE set F_RDLV_SaleOrderQty=F_RDLV_AvailableQty where FENTRYID='{1}'", SaleOrderQty + SaleQty, AvailableFentryid);
                                            DBUtils.Execute(ctx, sql_uA);

                                            SaleQty = SaleQty - (AvailableQty - SaleOrderQty);//扣减订单剩余数量
                                        }
                                    }
                                }
                            }
                        }
                        #endregion


                    }
                }
            }
        }
        #region 预计可发量
        public void GetAvailableQuantity(Context ctx, string forgid, int Sdays)
        {
            //先删除当天的
            string RDLV_Date_Now = DateTime.Now.ToString("yyyy-MM-dd");

            string NDate = DateTime.Now.AddDays(-Sdays).ToString("yyyy-MM-dd");//删除多少天前的数据


            #region 执行删除
            //预计可发量  F_RDLV_Date='" + RDLV_Date_Now + "' and
            string sql_cc = @"/*dialect*/  select * from RDLV_t_AvailableQuantity where F_RDLV_OrgId='" + forgid + "' and ( F_RDLV_Date<='" + NDate + "' or F_RDLV_Date='" + DateTime.Now.ToString("yyyy-MM-dd") + "')";
            DataTable dt_Av = DBUtils.ExecuteDataSet(ctx, sql_cc).Tables[0];

            if (dt_Av != null && dt_Av.Rows.Count > 0)
            {
                for (int cc = 0; cc < dt_Av.Rows.Count; cc++)
                {
                    string sql_aa = @"/*dialect*/  delete from RDLV_t_AvailableQuantityE where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_aa);

                    string sql_bb = @"/*dialect*/  delete from RDLV_t_AvailableQuantity where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_bb);
                }
            }


            #endregion


            //循环月计划，直至月计划不存在，最后查询隔月计划
            DataTable dt_bak = new DataTable();
            int i = 0;
            int Fyear = 0;
            int FMonth = 0;
            while (true)
            {
                DateTime dateTime = DateTime.Now.AddMonths(i);//时间
                Fyear = dateTime.Year;//年份
                FMonth = dateTime.Month;//月份

                #region  当月有计划
                //获取月计划  将生产单位数量换算成基本单位数量
                string sql = @"/*dialect*/select a.FID,[FBILLNO],[FDOCUMENTSTATUS],[F_RDLV_YEAR],[F_RDLV_MONTH],[F_RDLV_ORGID]
                ,[FEntryID],[F_RDLV_PRODUCT],
                [F_RDLV_QTY]*ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_QTY,
                [F_RDLV_TWOQTY]*ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_TWOQTY,
                [F_RDLV_THREEQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_THREEQTY,
                [F_RDLV_FOURQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_FOURQTY,
                [F_RDLV_MONTHQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_MONTHQTY,
                [F_RDLV_PROORGID]  from RDLV_t_MonProductionPlan a,RDLV_t_MonProductionPlanE b
               where a.fid=b.fid and F_RDLV_OrgId='" + forgid + "' and F_RDLV_Year='" + Fyear + "' and F_RDLV_Month='" + FMonth + "'   and FDOCUMENTSTATUS='C'" +
               " and (F_RDLV_QTY>0 or  F_RDLV_TWOQTY>0 or  F_RDLV_THREEQTY>0 or  F_RDLV_FOURQTY>0 or  F_RDLV_MONTHQTY>0)";//增加测试[F_RDLV_PRODUCT
                DataTable dt = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    int days = 1;
                    if (i == 0)
                    {
                        days = dateTime.Day;
                    }

                    for (int a = days; a <= DateTime.DaysInMonth(Fyear, FMonth); a++)
                    {
                        dateTime = Convert.ToDateTime(Fyear + "-" + FMonth + "-" + a);

                        //单元周期设置为4个周期每月
                        //1-7为周期1
                        //8-14为周期2
                        //15-21为周期3
                        //22-月底为周期4
                        //存在物料没有月计划，但是有周计划（生产订单）
                        //循环月计划
                        foreach (DataRow item in dt.Rows)
                        {
                            //查询销售订单未关闭的存在多少计划跟踪号
                            //销售订单
                            string sql_Or = string.Format(@"/*dialect*/ select '" + item["F_RDLV_Product"] + "' FMaterialId,'' FMTONO  union all" +
                                "   select F_QUQY_MATERIAL,FMTONO  from T_SAL_ORDER a  " +
                            " inner join T_SAL_ORDERENTRY b on a.FID=b.FID " +
                            "inner join T_SAL_ORDERENTRY_R d on b.fentryid = d.fentryid " + // and FCANOUTQTY>0 
                            " where  FDOCUMENTSTATUS='C'   and FCloseStatus='A' and FMTONO<>'' and F_QUQY_MATERIAL='" + item["F_RDLV_Product"] + "'  and FStockOrgId='" + item["F_RDLV_ProOrgId"].ToString() + "' " +
                            "group by F_QUQY_MATERIAL,FMTONO");
                            DataTable dt_sa = DBUtils.ExecuteDataSet(ctx, sql_Or).Tables[0];

                            if (dt_sa.Rows.Count > 0)
                            {
                                foreach (DataRow DataRowSa in dt_sa.Rows)
                                {

                                    string RDLV_Date = dateTime.ToString("yyyy-MM-dd");
                                    if (RDLV_Date == "2024-08-01")
                                    {
                                        string aa = "";
                                    }
                                    string InFID = "";
                                    //查询预计入
                                    sql = @"/*dialect*/  select F_QLTK_BaseQty,FID from QLTK_t_PreRecorded where CONVERT(varchar(100), F_QLTK_DATE, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_QLTK_OrgId='" + item["F_RDLV_ProOrgId"].ToString() + "'" +
                                        " and F_QLTK_Material='" + item["F_RDLV_Product"].ToString() + "' and F_QLTK_Moto='" + DataRowSa["FMTONO"].ToString() + "' and CONVERT(varchar(100), F_QLTK_InDate, 23)='" + dateTime.ToString("yyyy-MM-dd") + "'";
                                    DataTable dt_OrderNot = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                                    decimal OrderNotInQty = 0; //预计入
                                    if (dt_OrderNot != null && dt_OrderNot.Rows.Count > 0)
                                    {
                                        OrderNotInQty = Convert.ToDecimal(dt_OrderNot.Rows[0]["F_QLTK_BaseQty"]);
                                        InFID = dt_OrderNot.Rows[0]["FID"].ToString();
                                    }

                                    decimal DayInQty = 0; //当日入库量


                                    //查询当日入库量  查询生产订单截止日期为当前时间之前的未入库数量+当日生产入库单数量
                                    sql = @"/*dialect*/  select sum(FBASEPRDREALQTY) FRealQty from T_PRD_INSTOCK a, T_PRD_INSTOCKENTRY c,T_PRD_INSTOCKENTRY_A b where a.fid = c.fid and c.fentryid=b.fentryid " +
                                    " and FDocumentStatus='C' and FCancelStatus='A' and FMTONO='" + DataRowSa["FMTONO"] + "' and CONVERT(varchar(100), FDATE, 23)= '" + RDLV_Date + "' and FMaterialId = '" + item["F_RDLV_Product"] + "' and(FInStockType = '1' or FInStockType = '5') and FStockOrgId = '" + item["F_RDLV_ProOrgId"].ToString() + "' " +
                                    " group by FMaterialId";
                                    DataTable dt_DayIn = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];

                                    if (dt_DayIn != null && dt_DayIn.Rows.Count > 0)
                                    {
                                        DayInQty = Convert.ToDecimal(dt_DayIn.Rows[0]["FRealQty"]);
                                    }


                                    decimal ShouldQty = DayInQty + OrderNotInQty; //当日应该入   作为周期单元线的值扣减


                                    decimal InventoryQty = 0; //即时库存量

                                    //查询当前库存 去除已占用（已发票通知，未出库）=预计可发量
                                    string sql_Inventory = string.Format(@"/*dialect*/select FMaterialId,FStockOrgId,sum(FBaseQty) FBaseQty from T_STK_INVENTORY where  FMTONO='{2}'  and FMaterialId in (select FMASTERID from T_BD_MATERIAL where FMaterialId='{0}' and FUSEORGID='{1}')  and FStockOrgId='{1}' 
                            and FSTOCKID in(select FSTOCKID from t_BD_Stock where FAvailablePicking='1' and FDefStockStatusId='10000') group by FMaterialId,FStockOrgId", item["F_RDLV_Product"].ToString(), item["F_RDLV_ProOrgId"].ToString(), DataRowSa["FMTONO"].ToString());
                                    DataTable dt_Inventory = DBUtils.ExecuteDataSet(ctx, sql_Inventory).Tables[0];
                                    if (dt_Inventory != null && dt_Inventory.Rows.Count > 0)
                                    {
                                        InventoryQty = Convert.ToDecimal(dt_Inventory.Rows[0]["FBaseQty"]);

                                    }
                                    //查询预计出
                                    decimal issuedQty = 0; //预计出

                                    string OutFID = "";
                                    string sql_issued = string.Format(@"/*dialect*/  select F_QLTK_BaseQty,FID from QLTK_t_OutboundQuantity where CONVERT(varchar(100), F_QLTK_DATE, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_QLTK_OrgId='" + item["F_RDLV_ProOrgId"].ToString() + "'" +
                                       " and F_QLTK_Material='" + item["F_RDLV_Product"].ToString() + "' and F_QLTK_Moto='" + DataRowSa["FMTONO"].ToString() + "' and  CONVERT(varchar(100), F_QLTK_InDate, 23)='" + dateTime.ToString("yyyy-MM-dd") + "'");
                                    DataTable dt_issued = DBUtils.ExecuteDataSet(ctx, sql_issued).Tables[0];
                                    if (dt_issued != null && dt_issued.Rows.Count > 0)
                                    {
                                        issuedQty = Convert.ToDecimal(dt_issued.Rows[0]["F_QLTK_BaseQty"]);
                                        OutFID = dt_issued.Rows[0]["FID"].ToString();

                                    }

                                    //需要增加判断是否当月1号是在一次执行计划内执行，则需要取前一天的库存
                                    //查前一天剩余多少 可发量
                                    sql = @"/*dialect*/  select * from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid 
                                    and CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "'  and F_RDLV_Materal='" + item["F_RDLV_Product"].ToString() + "' and F_RDLV_OrgIdE='" + item["F_RDLV_ProOrgId"].ToString() + "'";
                                    DataTable dt_22 = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];


                                    //预计可发量 
                                    decimal AvailableQty = 0;
                                    if (a == days && (dt_22 == null || dt_22.Rows.Count <= 0))
                                    {   // 即时库存-预计出+预计入
                                        AvailableQty = InventoryQty - issuedQty + OrderNotInQty;
                                    }
                                    else
                                    {
                                        //查前一天剩余多少 可发量
                                        sql = @"/*dialect*/  select 
                           isnull( (select F_RDLV_AvailableQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal),0) F_RDLV_AvailableQty
                            from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid and CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_QLTK_Tracking='" + DataRowSa["FMTONO"].ToString() + "' " +
                            " and CONVERT(varchar(100), F_RDLV_Datee, 23)<='" + dateTime.AddDays(-1).ToString("yyyy-MM-dd") + "' and F_RDLV_Materal='" + item["F_RDLV_Product"].ToString() + "' and F_RDLV_OrgIdE='" + item["F_RDLV_ProOrgId"].ToString() + "' order by fentryid desc";
                                        DataTable dt_11 = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                                        decimal QyAvailableQty = 0;
                                        if (dt_11 != null && dt_11.Rows.Count > 0)
                                        {
                                            QyAvailableQty = Convert.ToDecimal(dt_11.Rows[0][0]);
                                        }

                                        //前天剩余可发量-预计出+预计入
                                        AvailableQty = QyAvailableQty + OrderNotInQty - issuedQty;
                                        InventoryQty = 0;
                                    }
                                    decimal DyxZR = 0;//单元线预计入


                                    //单元线的值计算
                                    //1.首先指定每个周期得开始和结束日期
                                    //2.判断当前执行时间再哪个时间段
                                    //3.然后确定本周期生产的数量，并获取单元线计划总值，计算后得到单元线的值
                                    //4.如果当前日期是周期的最后一天，则把当前单元线剩余数量放到预计入
                                    //5.如果当前日期是周期的第一天则获取上一周期剩余单元线得值，加上当前的
                                    string[] arrDateStart = new string[4]; //周期开始日期
                                    string[] arrDateEnd = new string[4];//周期结束日期
                                    arrDateStart[0] = Fyear + "-" + FMonth + "-" + "01";
                                    arrDateStart[1] = Fyear + "-" + FMonth + "-" + "08";
                                    arrDateStart[2] = Fyear + "-" + FMonth + "-" + "15";
                                    arrDateStart[3] = Fyear + "-" + FMonth + "-" + "22";
                                    arrDateEnd[0] = Fyear + "-" + FMonth + "-" + "07";
                                    arrDateEnd[1] = Fyear + "-" + FMonth + "-" + "14";
                                    arrDateEnd[2] = Fyear + "-" + FMonth + "-" + "21";
                                    arrDateEnd[3] = Fyear + "-" + FMonth + "-" + DateTime.DaysInMonth(Fyear, FMonth);

                                    //查前一天剩余多少 单元线值
                                    sql = @"/*dialect*/  select 
                           (select F_RDLV_UnitQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal) F_RDLV_UnitQty,
                           (select F_RDLV_HideUnitQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal) F_RDLV_HideUnitQty
                            from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid  
                            and CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "'  and F_RDLV_Materal='" + item["F_RDLV_Product"].ToString() + "' and F_RDLV_OrgIdE='" + item["F_RDLV_ProOrgId"].ToString() + "' order by fentryid desc";
                                    DataTable dt_In = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];// and F_QLTK_Tracking=''
                                    decimal TopQty = 0; //前一天单元线值
                                    decimal HideQty = 0;//隐藏的单元线值
                                    if (dt_In != null && dt_In.Rows.Count > 0)
                                    {
                                        TopQty = Convert.ToDecimal(dt_In.Rows[0]["F_RDLV_UnitQty"]);
                                        HideQty = Convert.ToDecimal(dt_In.Rows[0]["F_RDLV_HideUnitQty"]);
                                    }
                                    else//前一天没有当日可发数据，单元线的值取计划的总值
                                    {

                                    }

                                    #region 第一周期
                                    //第一周期
                                    if (dateTime >= Convert.ToDateTime(arrDateStart[0]) && dateTime <= Convert.ToDateTime(arrDateEnd[0]))
                                    {
                                        //当前时间是第一个周期的第一天
                                        if (dateTime == Convert.ToDateTime(arrDateStart[0]))
                                        {
                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            if (HideQty < 0)
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_Qty"]) + HideQty;
                                                //如果上个周期超出了单元线的值，那下个周期单元线的值要减去上个周期超出的
                                            }
                                            else
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_Qty"]);

                                            }

                                            HideQty = HideQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_Qty"]);
                                        }
                                        //当前时间是第一个周期的最后一天
                                        else if (dateTime == Convert.ToDateTime(arrDateEnd[0]))
                                        {

                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_Qty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_Qty"]);
                                            }


                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;
                                            //如果当前日期是周期的最后一天，则把当前单元线剩余数量放到预计入
                                            if (TopQty > 0)
                                            {
                                                AvailableQty = AvailableQty + TopQty;
                                                DyxZR = DyxZR + TopQty;
                                                TopQty = 0;
                                                HideQty = 0;
                                            }

                                        }
                                        else
                                        {

                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_Qty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_Qty"]);
                                            }

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;


                                        }
                                    }
                                    #endregion

                                    #region 第二周期
                                    //第一周期
                                    if (dateTime >= Convert.ToDateTime(arrDateStart[1]) && dateTime <= Convert.ToDateTime(arrDateEnd[1]))
                                    {
                                        //当前时间是第一个周期的第一天
                                        if (dateTime == Convert.ToDateTime(arrDateStart[1]))
                                        {

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            if (HideQty < 0)
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_TwoQty"]) + HideQty;
                                                //如果上个周期超出了单元线的值，那下个周期单元线的值要减去上个周期超出的
                                            }
                                            else
                                            {

                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_TwoQty"]);

                                            }

                                            HideQty = HideQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_TwoQty"]);

                                        }
                                        //当前时间是第一个周期的最后一天
                                        else if (dateTime == Convert.ToDateTime(arrDateEnd[1]))
                                        {
                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_TwoQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_TwoQty"]);
                                            }


                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;


                                            //如果当前日期是周期的最后一天，则把当前单元线剩余数量放到预计入
                                            if (TopQty > 0)
                                            {
                                                AvailableQty = AvailableQty + TopQty;
                                                DyxZR = DyxZR + TopQty;
                                                TopQty = 0;
                                                HideQty = 0;
                                            }
                                        }
                                        else
                                        {
                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_TwoQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_TwoQty"]);
                                            }

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;



                                        }
                                    }
                                    #endregion

                                    #region 第三周期
                                    //第一周期
                                    if (dateTime >= Convert.ToDateTime(arrDateStart[2]) && dateTime <= Convert.ToDateTime(arrDateEnd[2]))
                                    {
                                        //当前时间是第一个周期的第一天
                                        if (dateTime == Convert.ToDateTime(arrDateStart[2]))
                                        {

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            if (HideQty < 0)
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_ThreeQty"]) + HideQty;
                                                //如果上个周期超出了单元线的值，那下个周期单元线的值要减去上个周期超出的
                                            }
                                            else
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_ThreeQty"]);

                                            }

                                            HideQty = HideQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_ThreeQty"]);

                                        }
                                        //当前时间是第一个周期的最后一天
                                        else if (dateTime == Convert.ToDateTime(arrDateEnd[2]))
                                        {
                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_ThreeQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_ThreeQty"]);
                                            }

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;

                                            //如果当前日期是周期的最后一天，则把当前单元线剩余数量放到预计入
                                            if (TopQty > 0)
                                            {
                                                AvailableQty = AvailableQty + TopQty;
                                                DyxZR = DyxZR + TopQty;
                                                TopQty = 0;
                                                HideQty = 0;
                                            }

                                        }
                                        else
                                        {

                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_ThreeQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_ThreeQty"]);
                                            }


                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;

                                        }
                                    }
                                    #endregion

                                    #region 第四周期
                                    //第一周期
                                    if (dateTime >= Convert.ToDateTime(arrDateStart[3]) && dateTime <= Convert.ToDateTime(arrDateEnd[3]))
                                    {
                                        //当前时间是第一个周期的第一天
                                        if (dateTime == Convert.ToDateTime(arrDateStart[3]))
                                        {
                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            if (HideQty < 0)
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_FourQty"]) + HideQty;
                                                //如果上个周期超出了单元线的值，那下个周期单元线的值要减去上个周期超出的
                                            }
                                            else
                                            {
                                                TopQty = TopQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_FourQty"]);

                                            }

                                            HideQty = HideQty - ShouldQty + Convert.ToDecimal(item["F_RDLV_FourQty"]);

                                        }
                                        //当前时间是第一个周期的最后一天
                                        else if (dateTime == Convert.ToDateTime(arrDateEnd[3]))
                                        {
                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_FourQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_FourQty"]);
                                            }


                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;
                                            //如果当前日期是周期的最后一天，则把当前单元线剩余数量放到预计入
                                            if (TopQty > 0)
                                            {
                                                AvailableQty = AvailableQty + TopQty;
                                                DyxZR = DyxZR + TopQty;
                                                TopQty = 0;
                                                HideQty = 0;
                                            }


                                        }
                                        else
                                        {
                                            if (dt_In != null && dt_In.Rows.Count > 0)
                                            { }
                                            else//前一天没有当日可发数据，单元线的值取计划的总值
                                            {
                                                TopQty = Convert.ToDecimal(item["F_RDLV_FourQty"]);
                                                HideQty = Convert.ToDecimal(item["F_RDLV_FourQty"]);
                                            }

                                            //周期的第一天用前一天单元线得值，减去当日生产的+本周期的计划值，计算出当日
                                            TopQty = TopQty - ShouldQty;
                                            HideQty = HideQty - ShouldQty;


                                        }
                                    }

                                    if (TopQty < 0)//单元线的值最小为零，为负数，增加字段单独记录
                                    {
                                        TopQty = 0;
                                    }
                                    #endregion

                                    DateTime datetime1 = DateTime.Now;


                                    decimal OrderNotInQty1 = OrderNotInQty; //预计入
                                    decimal AvailableQty1 = AvailableQty;//预计可发量
                                    decimal TopQty1 = TopQty;//周期单元线
                                    decimal HideQty1 = HideQty;//周期单元线隐藏值
                                    decimal InventoryQty1 = InventoryQty; //即时库存
                                    decimal issuedQty1 = issuedQty; //预计出
                                    decimal DyxZR1 = DyxZR; //周期单元线预计转入


                                    //需要将数量转换成销售数量
                                    sql = @"/*dialect*/  select FSaleURNum/ FSaleURNom from t_BD_MaterialSale where FMATERIALID='" + item["F_RDLV_Product"].ToString() + "'";
                                    DataTable dt_UR = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                                    decimal ur = Convert.ToDecimal(dt_UR.Rows[0][0]);

                                    if (dt_UR != null && dt_UR.Rows.Count > 0 && ur > 0)
                                    {

                                        OrderNotInQty1 = OrderNotInQty / ur;
                                        AvailableQty1 = AvailableQty / ur;
                                        TopQty1 = TopQty / ur;
                                        HideQty1 = HideQty / ur;

                                        InventoryQty1 = InventoryQty / ur;
                                        issuedQty1 = issuedQty / ur;
                                        DyxZR1 = DyxZR / ur;
                                    }
                                    decimal Yujrhj; //预计入合计
                                    Yujrhj = DyxZR1 + OrderNotInQty1;
                                    if (Yujrhj > 0 || AvailableQty1 > 0 || InventoryQty1 > 0 || issuedQty1 > 0)
                                    {
                                        //进行插入当日预计可发量
                                        InsertData(ctx, datetime1, dateTime, item["F_RDLV_Product"].ToString(), 0, 0, OrderNotInQty1, AvailableQty1, TopQty1, item["F_RDLV_ProOrgId"].ToString(), HideQty1, DataRowSa["FMTONO"].ToString(), InventoryQty1, OrderNotInQty1, issuedQty1, DyxZR1, InFID, OutFID, Yujrhj);
                                    }


                                }
                            }

                        }
                    }
                }
                #endregion

                if (dt == null || dt.Rows.Count <= 0)
                {
                    if (i > 0)
                    {
                        break; //查询不到月计划了，退出循环，然后再下面循环外面获取最后一次查询到的月计划的隔月信息
                    }

                }

                i++;
            }
            #region 没有计划，只有订单的物料
            string sql1 = @"/*dialect*/  
                    select InFid,OutFid,F_QLTK_MATERIAL,F_QLTK_OrgId,F_QLTK_MOTO,F_QLTK_InDate,F_QLTK_DATE,InQty,OutQty from (
                    (select isnull(ab.FID,0) InFid,isnull(ac.FID,0) OutFid,
                    case when ab.F_QLTK_MATERIAL is null then ac.F_QLTK_MATERIAL else ab.F_QLTK_MATERIAL end F_QLTK_MATERIAL,
                    case when ab.F_QLTK_OrgId is null then ac.F_QLTK_OrgId else ab.F_QLTK_OrgId end F_QLTK_OrgId,
                    case when ab.F_QLTK_MOTO is null then ac.F_QLTK_MOTO else ab.F_QLTK_MOTO end F_QLTK_MOTO,
                    case when ab.F_QLTK_InDate is null then ac.F_QLTK_InDate else ab.F_QLTK_InDate end F_QLTK_InDate,
                    case when ab.F_QLTK_DATE is null then ac.F_QLTK_DATE else ab.F_QLTK_DATE end F_QLTK_DATE,
                    isnull(ab.F_QLTK_BaseQty,0) InQty,isnull(ac.F_QLTK_BaseQty,0) OutQty
                     from (
                    (select fid,F_QLTK_MATERIAL,F_QLTK_OrgId,F_QLTK_MOTO,F_QLTK_BaseQty,F_QLTK_DATE,F_QLTK_InDate from QLTK_t_PreRecorded a where CONVERT(varchar(100), F_QLTK_DATE, 23)=CONVERT(varchar(100), getdate(), 23) ) AB
                    full join 
                    (select fid,F_QLTK_MATERIAL,F_QLTK_OrgId,F_QLTK_MOTO,F_QLTK_BaseQty,F_QLTK_DATE,F_QLTK_InDate from QLTK_t_OutboundQuantity a where CONVERT(varchar(100), F_QLTK_DATE, 23)=CONVERT(varchar(100), getdate(), 23) ) AC
                    on AB.F_QLTK_MATERIAL=ac.F_QLTK_MATERIAL and ab.F_QLTK_MOTO=ac.F_QLTK_MOTO and ab.F_QLTK_OrgId=ac.F_QLTK_OrgId
                    and AB.F_QLTK_DATE=ac.F_QLTK_DATE and ab.F_QLTK_InDate=ac.F_QLTK_InDate 
                    )  
                    ) BC
                    left join (
                    select F_RDLV_Materal,F_QLTK_Tracking,F_RDLV_OrgIdE from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b
                     where a.fid=b.FID and CONVERT(varchar(100), F_RDLV_Date, 23)=CONVERT(varchar(100), getdate(), 23)) BD
                     on BC.F_QLTK_MATERIAL=BD.F_RDLV_Materal and F_QLTK_Tracking=F_QLTK_MOTO and F_QLTK_OrgId=F_RDLV_OrgIdE) where F_QLTK_OrgId='" + forgid + "' and BD.F_RDLV_MATERAL is null";//增加测试BC.F_QLTK_MATERIAL
            DataTable dt_Mo = DBUtils.ExecuteDataSet(ctx, sql1).Tables[0];

            if (dt_Mo != null && dt_Mo.Rows.Count > 0)
            {

                foreach (DataRow item in dt_Mo.Rows)
                {
                    DateTime dateTime_In = Convert.ToDateTime(item["F_QLTK_InDate"]); //预计入出日期

                    decimal OrderNotInQty = Convert.ToDecimal(item["InQty"]); //预计入

                    decimal InventoryQty = 0; //即时库存量

                    //查询当前库存 去除已占用（已发票通知，未出库）=预计可发量
                    string sql_Inventory = string.Format(@"/*dialect*/select FMaterialId,FStockOrgId,sum(FBaseQty) FBaseQty from T_STK_INVENTORY where   FMTONO='" + item["F_QLTK_MOTO"].ToString() + "' " +
                        " and  FMaterialId in (select FMASTERID from T_BD_MATERIAL where FMaterialId='{0}' and FUSEORGID='{1}')   and FStockOrgId='{1}'  " +
                " and FSTOCKID in(select FSTOCKID from t_BD_Stock where FAvailablePicking='1' and FDefStockStatusId='10000') group by FMaterialId,FStockOrgId", item["F_QLTK_MATERIAL"].ToString(), item["F_QLTK_OrgId"].ToString());

                    DataTable dt_Inventory = DBUtils.ExecuteDataSet(ctx, sql_Inventory).Tables[0];
                    if (dt_Inventory != null && dt_Inventory.Rows.Count > 0)
                    {
                        InventoryQty = Convert.ToDecimal(dt_Inventory.Rows[0]["FBaseQty"]);

                    }
                    //查询发货通知单 已发货未出库
                    decimal issuedQty = Convert.ToDecimal(item["OutQty"]); //已发货未出库



                    //预计可发量  即时库存-已发货通知未出库+当日入库量
                    decimal AvailableQty = 0; //已发货未出库

                    //查询执行当日是否已经插入过这个物料，如果插入过了，所有已经加过即时库存，就不再加了

                    string sql_Q = @"/*dialect*/  select * from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_RDLV_Materal='" + item["F_QLTK_MATERIAL"].ToString() + "'  and F_RDLV_OrgId='" + item["F_QLTK_OrgId"].ToString() + "' and F_QLTK_Tracking='" + item["F_QLTK_MOTO"].ToString() + "' and a.FID=b.FID";
                    DataTable dt_Q = DBUtils.ExecuteDataSet(ctx, sql_Q).Tables[0];

                    if (dt_Q != null && dt_Q.Rows.Count > 0)
                    {
                        //查询前一天剩余多少可发亮
                        string sql2 = @"/*dialect*/  select 
                           isnull( (select F_RDLV_AvailableQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal),0) F_RDLV_AvailableQty
                            from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid and CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and F_QLTK_Tracking='" + item["F_QLTK_MOTO"].ToString() + "' " +
              " and CONVERT(varchar(100), F_RDLV_Datee, 23)<='" + dateTime_In.AddDays(-1).ToString("yyyy-MM-dd") + "' and F_RDLV_Materal='" + item["F_QLTK_MATERIAL"].ToString() + "' and F_RDLV_OrgIdE='" + item["F_QLTK_OrgId"].ToString() + "' order by fentryid desc";
                        DataTable dt_11 = DBUtils.ExecuteDataSet(ctx, sql2).Tables[0];
                        decimal QyAvailableQty = 0;
                        if (dt_11 != null && dt_11.Rows.Count > 0)
                        {
                            QyAvailableQty = Convert.ToDecimal(dt_11.Rows[0][0]);
                        }


                        AvailableQty = QyAvailableQty + OrderNotInQty - issuedQty;
                        InventoryQty = 0;
                    }
                    else
                    {
                        AvailableQty = InventoryQty - issuedQty + OrderNotInQty;
                    }



                    DateTime datetime1 = DateTime.Now;


                    decimal OrderNotInQty1 = OrderNotInQty;
                    decimal AvailableQty1 = AvailableQty;

                    decimal InventoryQty1 = InventoryQty; //即时库存
                    decimal issuedQty1 = issuedQty; //预计出

                    //需要将数量转换成销售数量
                    string sql = @"/*dialect*/  select FSaleURNum/ FSaleURNom from t_BD_MaterialSale where FMATERIALID='" + item["F_QLTK_MATERIAL"].ToString() + "'";
                    DataTable dt_UR = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                    decimal ur = Convert.ToDecimal(dt_UR.Rows[0][0]);

                    if (dt_UR != null && dt_UR.Rows.Count > 0 && ur > 0)
                    {
                        issuedQty1 = issuedQty / ur;
                        InventoryQty1 = InventoryQty / ur;
                        OrderNotInQty1 = OrderNotInQty / ur;
                        AvailableQty1 = AvailableQty / ur;

                    }

                    //进行插入当日预计可发量
                    InsertData(ctx, datetime1, dateTime_In, item["F_QLTK_MATERIAL"].ToString(), 0, 0, OrderNotInQty1, AvailableQty1, 0, item["F_QLTK_OrgId"].ToString(), 0, item["F_QLTK_MOTO"].ToString(), InventoryQty1, OrderNotInQty1, issuedQty1, 0, item["InFid"].ToString(), item["OutFid"].ToString(), OrderNotInQty1);

                }

            }
            #endregion
            #region  隔月计划
            //插入隔月计划，或者最后一个月的计划，取隔月计划，全部放到隔月的最后一天
            DateTime dateTime_G = DateTime.Now.AddMonths(i - 1);//当月
                                                                //获取月计划
            Fyear = dateTime_G.Year;//年份
            FMonth = dateTime_G.Month;//月份

            //次月
            DateTime dateTime2 = DateTime.Now.AddMonths(i);//时间
            int Fyear2 = dateTime2.Year;//年份
            int FMonth2 = dateTime2.Month;//月份

            //隔月的最后一天
            string dti_g = Convert.ToDateTime(Fyear2 + "-" + FMonth2 + "-" + DateTime.DaysInMonth(Fyear2, FMonth2)).ToString("yyyy-MM-dd");
            //隔月的第一天
            string dti_E = Convert.ToDateTime(Fyear2 + "-" + FMonth2 + "-01").ToString("yyyy-MM-dd");


            var sql_1 = @"/*dialect*/select a.FID,[FBILLNO],[FDOCUMENTSTATUS],[F_RDLV_YEAR],[F_RDLV_MONTH],[F_RDLV_ORGID]
                ,[FEntryID],[F_RDLV_PRODUCT],
                [F_RDLV_QTY]*ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_QTY,
                [F_RDLV_TWOQTY]*ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_TWOQTY,
                [F_RDLV_THREEQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_THREEQTY,
                [F_RDLV_FOURQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_FOURQTY,
                [F_RDLV_MONTHQTY]* ISNULL((select FPRDURNUM/FPRDURNOM from t_BD_MaterialProduce where FMATERIALID=b.F_RDLV_PRODUCT),0) F_RDLV_MONTHQTY,[F_RDLV_PROORGID]  from RDLV_t_MonProductionPlan a,RDLV_t_MonProductionPlanE b
               where a.fid=b.fid  and F_RDLV_OrgId='" + forgid + "' and F_RDLV_Year='" + Fyear + "' and F_RDLV_Month='" + FMonth + "'   and FDOCUMENTSTATUS='C'";//增加测试F_RDLV_PRODUCT
            DataTable dt_1 = DBUtils.ExecuteDataSet(ctx, sql_1).Tables[0];
            if (dt_1 != null && dt_1.Rows.Count > 0)
            {

                foreach (DataRow item in dt_1.Rows)
                {
                    //查询当月入库量，根据生产入库单查询本月的入库单数量，然后+停止之前为当前天之前的未入库数量
                    decimal AccumulateInQty = 0; //当月入库量
                    //查询订单未入库量

                    decimal OrderNotInQty = 0; //预计入


                    AccumulateInQty = OrderNotInQty;


                    decimal AvailableQty = 0; //预计可发量
                    //上个月的最后一天
                    string detop = Convert.ToDateTime(Fyear + "-" + FMonth + "-" + DateTime.DaysInMonth(Fyear, FMonth)).ToString("yyyy-MM-dd");

                    //查前一天剩余多少 单元线值
                    sql_1 = @"/*dialect*/  select  
                   (select F_RDLV_UnitQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal) F_RDLV_UnitQty,
                   (select F_RDLV_HideUnitQty*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal) F_RDLV_HideUnitQty  from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid 
                   and  F_RDLV_Materal='" + item["F_RDLV_Product"].ToString() + "' " +
                   " and   CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(100), F_RDLV_DateE, 23)='" + detop + "'" +
                   "  and F_RDLV_OrgIdE='" + item["F_RDLV_ProOrgId"].ToString() + "' order by fentryid desc";
                    // and f_qltk_tracking=''

                    DataTable dt_In = DBUtils.ExecuteDataSet(ctx, sql_1).Tables[0];


                    //查询一共剩余多少预计可发量
                    string sql_2 = @"/*dialect*/  select  (select sum(F_RDLV_AvailableQty)*(FSaleURNum/FSaleURNom)  from t_BD_MaterialSale where FMATERIALID=b.F_RDLV_Materal) F_RDLV_AvailableQty
                   from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.fid 
                   and  F_RDLV_Materal='" + item["F_RDLV_Product"].ToString() + "' " +
                     " and  CONVERT(varchar(100), F_RDLV_Date, 23)='" + DateTime.Now.ToString("yyyy-MM-dd") + "' and CONVERT(varchar(100), F_RDLV_DateE, 23)='" + detop + "'" +
                     "  and F_RDLV_OrgIdE='" + item["F_RDLV_ProOrgId"].ToString() + "' group by F_RDLV_Materal";


                    decimal TopAvQty = 0;//前一天预计可发量的值
                    DataTable dt_topAvailableqty = DBUtils.ExecuteDataSet(ctx, sql_2).Tables[0];
                    if (dt_topAvailableqty != null && dt_topAvailableqty.Rows.Count > 0)
                    {
                        TopAvQty = Convert.ToDecimal(dt_topAvailableqty.Rows[0]["F_RDLV_AvailableQty"]);

                    }


                    decimal TopQty = 0; //前一天单元线值

                    if (dt_In != null && dt_In.Rows.Count > 0)
                    {
                        TopQty = Convert.ToDecimal(dt_In.Rows[0]["F_RDLV_UnitQty"]);
                    }

                    //查询隔月计划的数量
                    decimal MonthQty = Convert.ToDecimal(item["F_RDLV_MonthQty"]);
                    AvailableQty = TopQty + MonthQty;//预计入  上一节点剩余单元线值+隔月计划值

                    decimal AllAvailableQty = TopQty + MonthQty + TopAvQty;//总的预计可发量

                    TopQty = 0;

                    DateTime datetime1 = DateTime.Now;

                    decimal AccumulateInQty1 = AccumulateInQty;
                    decimal OrderNotInQty1 = OrderNotInQty;
                    decimal AvailableQty1 = AvailableQty;
                    decimal TopQty1 = TopQty;
                    decimal AllAvailableQty1 = AllAvailableQty;

                    //需要将数量转换成销售数量
                    string sql = @"/*dialect*/  select FSaleURNum/ FSaleURNom from t_BD_MaterialSale where FMATERIALID='" + item["F_RDLV_Product"].ToString() + "'";
                    DataTable dt_UR = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];
                    decimal ur = Convert.ToDecimal(dt_UR.Rows[0][0]);

                    if (dt_UR != null && dt_UR.Rows.Count > 0 && ur > 0)
                    {

                        AccumulateInQty1 = AccumulateInQty / ur;
                        OrderNotInQty1 = OrderNotInQty / ur;
                        AvailableQty1 = AvailableQty / ur;
                        TopQty1 = TopQty / ur;
                        AllAvailableQty1 = AllAvailableQty / ur;

                    }

                    decimal yjrkhj = AvailableQty1 + OrderNotInQty;
                    //进行插入当日预计可发量
                    InsertData(ctx, datetime1, Convert.ToDateTime(dti_g), item["F_RDLV_Product"].ToString(), 0, AccumulateInQty1, OrderNotInQty1, AllAvailableQty1, AvailableQty1, item["F_RDLV_ProOrgId"].ToString(), 0, "", 0, 0, 0, AvailableQty1, "", "", yjrkhj);
                }


            }
            #endregion


            #region 只有库存，没有预计出入及生产计划

            string sql_20240822 = string.Format(@"/*dialect*/ select bbb.FMATERIALID FMASTERID,FStockOrgId,FBaseQty,FMTONO,
(select FMATERIALID from T_BD_MATERIAL where FUSEORGID='{0}' and FMASTERID=bbb.FMATERIALID)  FMATERIALID from (
select F_RDLV_Materal,F_QLTK_Tracking,F_RDLV_OrgIdE,
(select FMASTERID from T_BD_MATERIAL where FUSEORGID='{0}' and FMaterialId=F_RDLV_Materal) Fmater
from RDLV_t_AvailableQuantity a,RDLV_t_AvailableQuantityE b where a.fid=b.FID 
and CONVERT(varchar(100), F_RDLV_Date, 23)=CONVERT(varchar(100), getdate(), 23) and F_RDLV_OrgId='{0}') aaa
right join 
(select FMaterialId,FStockOrgId,sum(FBaseQty) FBaseQty,FMTONO from T_STK_INVENTORY 
where   FMaterialId in (select FMASTERID from T_BD_MATERIAL aa1,t_BD_MaterialBase bb1 where aa1.FMATERIALID=bb1.FMATERIALID 
and (FCategoryID='168630' or FCategoryID='241')  and  aa1.FUSEORGID='{0}')   and FStockOrgId='{0}'
and FSTOCKID in(select FSTOCKID from t_BD_Stock where FAvailablePicking='1' and FDefStockStatusId='10000') 
group by FMaterialId,FStockOrgId,FMTONO) bbb
on  Fmater=FMaterialId and F_QLTK_Tracking=FMTONO and F_RDLV_OrgIdE=FStockOrgId
where aaa.F_RDLV_MATERAL is null and FBaseQty>0", forgid);

            DataTable dt_20240822 = DBUtils.ExecuteDataSet(ctx, sql_20240822).Tables[0];
            if (dt_20240822 != null && dt_20240822.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_20240822.Rows)
                {
                    InsertData(ctx, DateTime.Now, DateTime.Now, dr["FMATERIALID"].ToString(), 0, 0, 0, Convert.ToDecimal(dr["FBaseQty"]), 0, dr["FStockOrgId"].ToString(), 0, dr["FMTONO"].ToString(), Convert.ToDecimal(dr["FBaseQty"]), 0, 0, 0, "", "", 0);
                }
            }



            #endregion


            //修改排序
            string sql_Order = @"/*dialect*/  update a set a.fseq=b.idd from 
            (select ROW_NUMBER() over(order  by F_RDLV_datee) as idd,FEntryID from RDLV_t_AvailableQuantityE) b,RDLV_t_AvailableQuantityE a,RDLV_t_AvailableQuantity c
            where b.FEntryID=a.FEntryID and a.fid=c.fid and CONVERT(varchar(100), c.F_RDLV_Date, 23)=CONVERT(varchar(100), getdate(), 23)";
            DBUtils.Execute(ctx, sql_Order);


        }
        #endregion

        #region 预计入
        public void GetPreRecorded(string forgid, Context ctx, int Sdays)
        {

            //先删除当天的
            string RDLV_Date_Now = DateTime.Now.ToString("yyyy-MM-dd");


            string NDate = DateTime.Now.AddDays(-Sdays).ToString("yyyy-MM-dd");//删除多少天前的数据


            #region 执行删除

            //预计入 CONVERT(varchar(100), F_QLTK_Date, 23)='" + RDLV_Date_Now + "' and
            string sql_cc = @"/*dialect*/  select * from QLTK_t_PreRecorded where  F_QLTK_OrgId='" + forgid + "'  and (F_QLTK_Date<='" + NDate + "' or F_QLTK_Date='" + DateTime.Now.ToString("yyyy-MM-dd") + "')";
            DataTable dt_Av = DBUtils.ExecuteDataSet(ctx, sql_cc).Tables[0];

            if (dt_Av != null && dt_Av.Rows.Count > 0)
            {
                for (int cc = 0; cc < dt_Av.Rows.Count; cc++)
                {
                    string sql_aa = @"/*dialect*/  delete from QLTK_t_PreRecordedE where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_aa);

                    string sql_bb = @"/*dialect*/  delete from QLTK_t_PreRecorded where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_bb);
                }
            }

            #endregion


            string sql_po = string.Format(@"/*dialect*/ select FStockInOrgId,FMaterialId,FMTONO from T_PRD_MO a,T_PRD_MOENTRY b,T_PRD_MOENTRY_Q c, T_PRD_MOENTRY_A d where a.fid=b.fid 
            and b.fentryid=c.fentryid and FDocumentStatus='C'  and FCancelStatus='A' and FSTATUS!='5' and FSTATUS!='6' and FSTATUS!='7'
            and FBASENOSTOCKINQTY> 0   and b.fentryid=d.FENTRYID and FStockInOrgId='" + forgid + "'" + //增加测试fmaterialid
            " group by  FStockInOrgId,FMaterialId,FMTONO");
            DataTable dt_po = DBUtils.ExecuteDataSet(ctx, sql_po).Tables[0];

            if (dt_po != null && dt_po.Rows.Count > 0)
            {
                foreach (DataRow item in dt_po.Rows)
                {
                    string Product = item["FMaterialId"].ToString();//产品
                    string FMTONO = item["FMTONO"].ToString();//计划跟踪号
                    string ProOrgId = item["FStockInOrgId"].ToString();//组织

                    string sql_date = @"/*dialect*/ select FPlanFinishDate from T_PRD_MO a,T_PRD_MOENTRY b, T_PRD_MOENTRY_Q c, T_PRD_MOENTRY_A d where a.fid = b.fid
                    and b.fentryid = c.fentryid and FDocumentStatus = 'C'  and FCancelStatus = 'A' and FSTATUS!='5' and FSTATUS!='6' and FSTATUS!='7' 
                    and FBASENOSTOCKINQTY> 0   and b.fentryid = d.FENTRYID and FMaterialId='" + Product + "' and FMTONO='" + FMTONO + "' and FStockInOrgId='" + ProOrgId + "' " +
                    " order by FPlanFinishDate desc";
                    DataTable dt_date = DBUtils.ExecuteDataSet(ctx, sql_date).Tables[0];
                    if (dt_date != null && dt_date.Rows.Count > 0)
                    {
                        int QT = 0;
                        string dateTime = DateTime.Now.ToString("yyyy-MM-dd");//当前时间
                        string FDeliveryDate = Convert.ToDateTime(dt_date.Rows[0][0]).ToString("yyyy-MM-dd");//结束时间

                        while (true)
                        {
                            string addwhere = "";
                            dateTime = DateTime.Now.AddDays(QT).ToString("yyyy-MM-dd");
                            if (QT == 0)
                            {
                                addwhere = " and CONVERT(varchar(100), FPlanFinishDate, 23)<='" + dateTime + "'";
                            }
                            else
                            {
                                addwhere = " and CONVERT(varchar(100), FPlanFinishDate, 23)='" + dateTime + "'";
                            }
                            //查询订单未入库量（基本单位未入库数量）
                            string sql = @"/*dialect*/  select FBASENOSTOCKINQTY, " +
                                   " isnull(FBASENOSTOCKINQTY/(select FSaleURNum/ FSaleURNom from t_BD_MaterialSale where FMATERIALID='" + Product + "'),0) OrderNotInQtySale, " +
                                   " isnull(FBASENOSTOCKINQTY/(select FPrdURNum/ FPrdURNom from t_BD_MaterialProduce where FMATERIALID='" + Product + "'),0) OrderNotInQtyPo, " +
                                   " FBillNo,FDate,FQty,FPlanStartDate,FPlanFinishDate from T_PRD_MO a,T_PRD_MOENTRY b,T_PRD_MOENTRY_Q c, T_PRD_MOENTRY_A d where a.fid=b.fid " +
                         " and b.fentryid=c.fentryid and FDocumentStatus='C' and FMaterialId='" + Product + "' and FCancelStatus='A' " +
                         " and FMTONO='" + FMTONO + "' and FStockInOrgId = '" + ProOrgId + "' and FBASENOSTOCKINQTY> 0 and FSTATUS!='5' and FSTATUS!='6' and FSTATUS!='7'    and b.fentryid=d.FENTRYID " + addwhere + "";

                            DataTable dt_OrderNotInQty = DBUtils.ExecuteDataSet(ctx, sql).Tables[0];

                            //存在数据订单未入库量
                            if (dt_OrderNotInQty != null && dt_OrderNotInQty.Rows.Count > 0)
                            {
                                //插入单据头

                                decimal SumOrderNotInQtyBase = decimal.Parse(dt_OrderNotInQty.Compute("sum(FBASENOSTOCKINQTY)", "").ToString());
                                decimal SumOrderNotInQtySale = decimal.Parse(dt_OrderNotInQty.Compute("sum(OrderNotInQtySale)", "").ToString());
                                decimal SumOrderNotInQtyPo = decimal.Parse(dt_OrderNotInQty.Compute("sum(OrderNotInQtyPo)", "").ToString());
                                string FID = InsertPreRecordedData(ctx, DateTime.Now, Convert.ToDateTime(dateTime), Product, FMTONO, ProOrgId, SumOrderNotInQtyBase, SumOrderNotInQtySale, SumOrderNotInQtyPo);

                                foreach (DataRow item_NotInQty in dt_OrderNotInQty.Rows)
                                {

                                    decimal OrderNotInQtyBase = Convert.ToDecimal(item_NotInQty["FBASENOSTOCKINQTY"]); //订单未入库量  基本数量
                                    decimal OrderNotInQtySale = Convert.ToDecimal(item_NotInQty["OrderNotInQtySale"]); //订单未入库量  销售数量
                                    decimal OrderNotInQtyPo = Convert.ToDecimal(item_NotInQty["OrderNotInQtyPo"]); //订单未入库量  生产数量

                                    string FBillNo = item_NotInQty["FBillNo"].ToString();
                                    string FDate = item_NotInQty["FDate"].ToString();
                                    decimal FQty = Convert.ToDecimal(item_NotInQty["FQty"]);
                                    string FPlanStartDate = item_NotInQty["FPlanStartDate"].ToString();
                                    string FPlanFinishDate = item_NotInQty["FPlanFinishDate"].ToString();


                                    //进行插入当日预计可发量
                                    InsertPreRecordedEData(ctx, FID, FBillNo, FDate, FQty, FPlanStartDate, FPlanFinishDate, OrderNotInQtyBase, OrderNotInQtySale, OrderNotInQtyPo);
                                }

                            }
                            QT++;
                            if (Convert.ToDateTime(FDeliveryDate) <= Convert.ToDateTime(dateTime))
                            {
                                break;
                            }
                        }

                    }
                }
            }
        }
        #endregion
        #region 预计出
        public void OutboundQuantity(Context ctx, string forgid, int Sdays)
        {

            //先删除当天的
            string RDLV_Date_Now = DateTime.Now.ToString("yyyy-MM-dd");

            string NDate = DateTime.Now.AddDays(-Sdays).ToString("yyyy-MM-dd");//删除多少天前的数据

            //(select  FMATERIALID from T_BD_MATERIAL where FMASTERID =
            //(select FMASTERID from T_BD_MATERIAL ab where ab.FMATERIALID = AA.FMaterialID) and FUSEORGID = '" + forgid + "' ) "+
            #region 执行删除

            //预计出 CONVERT(varchar(100), F_QLTK_DATE, 23)='" + RDLV_Date_Now + "' and
            string sql_cc = @"/*dialect*/  select * from QLTK_t_OutboundQuantity where  F_QLTK_OrgId='" + forgid + "'  and (F_QLTK_Date<='" + NDate + "' or F_QLTK_Date='" + DateTime.Now.ToString("yyyy-MM-dd") + "') ";
            DataTable dt_Av = DBUtils.ExecuteDataSet(ctx, sql_cc).Tables[0];

            if (dt_Av != null && dt_Av.Rows.Count > 0)
            {
                for (int cc = 0; cc < dt_Av.Rows.Count; cc++)
                {
                    string sql_aa = @"/*dialect*/  delete from QLTK_t_OutboundQuantityE where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_aa);

                    string sql_bb = @"/*dialect*/  delete from QLTK_t_OutboundQuantity where fid='" + dt_Av.Rows[cc]["FID"].ToString() + "'";
                    DBUtils.Execute(ctx, sql_bb);
                }
            }

            #endregion
            //查询所有存在预计出的物料、组织、计划跟踪号   发货通知单关联的是发货组织，销售订单关联的是销售组织，需要更新销售订单物料
            string str_1 = @"/*dialect*/ select FDeliveryOrgID,
            
             FMaterialID,FMTONO from(  " +
            " select FDeliveryOrgID,FMaterialID,FMTONO " +
            " from T_SAL_DELIVERYNOTICE a,T_SAL_DELIVERYNOTICEENTRY b,  " +
            " T_SAL_DELIVERYNOTICEENTRY_E c  " +
            " where a.fid=b.fid and b.fentryid=c.fentryid " +
            " and b.FCLOSESTATUS = 'A' and FDocumentStatus='C' and (FBASEUNITQTY-FSTOCKBASESUMOUTQTY)>0 " +
            " group by FDeliveryOrgID,FMaterialID,FMTONO " +
            " union all " +
            " select FStockOrgId,F_QUQY_MATERIAL,FMTONO " +
            " from T_SAL_ORDER a,T_SAL_ORDERENTRY b,  " +
            " T_SAL_ORDERENTRY_R c " +
            " where a.fid=b.fid and b.fentryid=c.fentryid " +
            " and a.FCLOSESTATUS = 'A' and FDocumentStatus='C' and FStockBaseCanOutQty>0 and F_QUQY_MATERIAL<>0 " +
            " group by FStockOrgId,F_QUQY_MATERIAL,FMTONO) AA where FDeliveryOrgID='" + forgid + "' " + //增加测试fmaterialid
            " group by FDeliveryOrgID,FMaterialID,FMTONO";

            DataTable dt_1 = DBUtils.ExecuteDataSet(ctx, str_1).Tables[0];
            if (dt_1 != null && dt_1.Rows.Count > 0)
            {

                foreach (DataRow item in dt_1.Rows)
                {
                    //查询每个物料的最后的要货日期，从开始时间开始循环，知道最后的要货日期结束
                    string str_2 = @"/*dialect*/ select FDeliveryDate from (
                    select FDeliveryDate
                    from T_SAL_DELIVERYNOTICE a,T_SAL_DELIVERYNOTICEENTRY b, 
                    T_SAL_DELIVERYNOTICEENTRY_E c " +
                    " where a.fid=b.fid and b.fentryid=c.fentryid and FDeliveryOrgID='" + item["FDeliveryOrgID"].ToString() + "'  and (FBASEUNITQTY-FSTOCKBASESUMOUTQTY)>0 " +
                    " and FMaterialID = '" + item["FMaterialID"].ToString() + "'" +
                    " and b.FCLOSESTATUS = 'A' and FDocumentStatus = 'C' and FMTONO = '" + item["FMTONO"] + "'" +
                    " union all" +
                    " select FDELIVERYDATE" +
                    " from T_SAL_ORDER a,T_SAL_ORDERENTRY b," +
                    " T_SAL_ORDERENTRY_R c,T_SAL_ORDERENTRY_D d" +
                    " where a.fid = b.fid and b.fentryid = c.fentryid and b.fentryid = d.fentryid and FStockOrgId = '" + item["FDeliveryOrgID"].ToString() + "'  and FStockBaseCanOutQty> 0 and F_QUQY_MATERIAL<>0 " +
                    " and F_QUQY_MATERIAL = '" + item["FMaterialID"].ToString() + "'" +
                    " and a.FCLOSESTATUS = 'A' and FDocumentStatus = 'C' and FMTONO = '" + item["FMTONO"] + "'" +
                    " ) AAA order by FDeliveryDate desc";
                    DataTable dt_2 = DBUtils.ExecuteDataSet(ctx, str_2).Tables[0];
                    if (dt_2 != null && dt_2.Rows.Count > 0)
                    {
                        int QT = 0;
                        string dateTime = DateTime.Now.ToString("yyyy-MM-dd");//当前时间
                        string FDeliveryDate = Convert.ToDateTime(dt_2.Rows[0][0]).ToString("yyyy-MM-dd");//结束时间

                        while (true)
                        {
                            string addwhere = "";
                            dateTime = DateTime.Now.AddDays(QT).ToString("yyyy-MM-dd");
                            if (QT == 0)
                            {
                                addwhere = " and CONVERT(varchar(100), FDeliveryDate, 23)<='" + dateTime + "'";
                            }
                            else
                            {
                                addwhere = "  and CONVERT(varchar(100), FDeliveryDate, 23)='" + dateTime + "'";
                            }


                            string str_3 = @"/*dialect*/ select FBillNo,FCustomerID,F_DEV_Saler,FDate,FQty,FDeliveryDate,FNoBaseQty,OrderNotInQtySale,OrderNotInQtyPo,FbillName,FMaterialID,FMTONO,FDeliveryOrgID from (
                    select FBillNo,FCustomerID,F_DEV_Saler,FDate,FQty,FDeliveryDate,(FBASEUNITQTY-FSTOCKBASESUMOUTQTY) FNoBaseQty, " +
                    " isnull((FBASEUNITQTY-FSTOCKBASESUMOUTQTY)/(select FSaleURNum/ FSaleURNom from t_BD_MaterialSale where FMATERIALID='" + item["FMaterialID"].ToString() + "'),0) OrderNotInQtySale," +
                    " isnull((FBASEUNITQTY - FSTOCKBASESUMOUTQTY) / (select FPrdURNum / FPrdURNom from t_BD_MaterialProduce where FMATERIALID = '" + item["FMaterialID"].ToString() + "'),0) OrderNotInQtyPo," +
                    " '发货通知单' FbillName,FMaterialID,FMTONO,FDeliveryOrgID " +
                    " from T_SAL_DELIVERYNOTICE a, T_SAL_DELIVERYNOTICEENTRY b, " +
                    " T_SAL_DELIVERYNOTICEENTRY_E c" +
                    "     where a.fid = b.fid and b.fentryid = c.fentryid and FDeliveryOrgID = '" + item["FDeliveryOrgID"].ToString() + "'  and(FBASEUNITQTY - FSTOCKBASESUMOUTQTY) > 0" +
                      "   and FMaterialID = '" + item["FMaterialID"].ToString() + "'" +
                        " and b.FCLOSESTATUS = 'A' and FDocumentStatus = 'C' and FMTONO = '" + item["FMTONO"] + "'" +
                    " union all" +
                    " select FBillNo, FCustId, F_DEV_Saler, FDate, FQty, FDELIVERYDATE, FStockBaseCanOutQty FNoBaseQty," +
                    " isnull(FStockBaseCanOutQty / (select FSaleURNum / FSaleURNom from t_BD_MaterialSale where FMATERIALID = '" + item["FMaterialID"].ToString() + "'),0) OrderNotInQtySale," +
                    " isnull(FStockBaseCanOutQty / (select FPrdURNum / FPrdURNom from t_BD_MaterialProduce where FMATERIALID = '" + item["FMaterialID"].ToString() + "'),0) OrderNotInQtyPo," +
                    " '销售订单' FbillName,F_QUQY_MATERIAL,FMTONO,FStockOrgId" +
                    " from T_SAL_ORDER a, T_SAL_ORDERENTRY b," +
                    " T_SAL_ORDERENTRY_R c, T_SAL_ORDERENTRY_D d" +
                    "  where a.fid = b.fid and b.fentryid = c.fentryid and b.fentryid = d.fentryid  and FStockOrgId = '" + item["FDeliveryOrgID"].ToString() + "'  and FStockBaseCanOutQty> 0" +
                     "    and F_QUQY_MATERIAL = '" + item["FMaterialID"].ToString() + "'" +
                      "   and a.FCLOSESTATUS = 'A' and FDocumentStatus = 'C' and FMTONO = '" + item["FMTONO"] + "'" +
                       "  ) AAA where 1=1 " + addwhere + "";


                            DataTable dt_3 = DBUtils.ExecuteDataSet(ctx, str_3).Tables[0];
                            if (dt_3 != null && dt_3.Rows.Count > 0)
                            {
                                //插入表头
                                decimal SumOrderNotInQtyBase = decimal.Parse(dt_3.Compute("sum(FNoBaseQty)", "").ToString());
                                decimal SumOrderNotInQtySale = decimal.Parse(dt_3.Compute("sum(OrderNotInQtySale)", "").ToString());
                                decimal SumOrderNotInQtyPo = decimal.Parse(dt_3.Compute("sum(OrderNotInQtyPo)", "").ToString());
                                string Fid = InsertOutboundQuantityData(ctx, DateTime.Now, Convert.ToDateTime(dateTime), item["FMaterialID"].ToString(), item["FMTONO"].ToString(), item["FDeliveryOrgID"].ToString(),
                                    SumOrderNotInQtyBase, SumOrderNotInQtySale, SumOrderNotInQtyPo);

                                foreach (DataRow item_2 in dt_3.Rows)
                                {
                                    //插入表体

                                    InsertOutboundQuantityEData(ctx, Fid, item_2["FBillNo"].ToString(), item_2["FDate"].ToString(), Convert.ToDecimal(item_2["FQty"]),
                                      item_2["FDeliveryDate"].ToString(), Convert.ToDecimal(item_2["FNoBaseQty"]), Convert.ToDecimal(item_2["OrderNotInQtySale"]), Convert.ToDecimal(item_2["OrderNotInQtyPo"])
                                      , item_2["FbillName"].ToString(), item_2["FCustomerID"].ToString(), item_2["F_DEV_Saler"].ToString());
                                }
                            }
                            QT++;
                            if (Convert.ToDateTime(FDeliveryDate) <= Convert.ToDateTime(dateTime))
                            {
                                break;
                            }


                        }



                    }



                }
            }

        }
        #endregion
        /// <summary>
        /// 插入预计出 单据头
        /// </summary>
        public string InsertOutboundQuantityData(Context context, DateTime dateTime, DateTime dateTime1, string F_RDLV_Materal, string FMTONO, string ProOrgId, decimal SumOrderNotInQtyBase, decimal SumOrderNotInQtySale, decimal SumOrderNotInQtyPo)
        {

            string RDLV_Date = dateTime.ToString("yyyy-MM-dd");
            string FID = "";
            //首先判断当日是否存在单据头数据，如果存在直接插入单据体，不存在，先插入单据头
            string sql = @"/*dialect*/  select * from QLTK_t_OutboundQuantity where CONVERT(varchar(100), F_QLTK_DATE, 23)='" + RDLV_Date + "' and F_QLTK_Material='" + F_RDLV_Materal + "' and F_QLTK_Moto='" + FMTONO + "' and F_QLTK_OrgId='" + ProOrgId + "'";
            DataTable dt = DBUtils.ExecuteDataSet(context, sql).Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                FID = dt.Rows[0][0].ToString();

            }
            else
            {
                //插入单据头

                string sql_FID = @"/*dialect*/  insert into Z_QLTK_t_OutboundQuantity(column1)  values(1)";
                DBUtils.Execute(context, sql_FID);

                sql = @"/*dialect*/   select Id from Z_QLTK_t_OutboundQuantity";
                DataTable dt_1 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

                sql_FID = @"/*dialect*/  delete from Z_QLTK_t_OutboundQuantity";
                DBUtils.Execute(context, sql_FID);

                //查询计量单位
                string sql_mate = @"/*dialect*/ select FBaseUnitId,FSaleUnitId,FProduceUnitId from t_BD_MaterialBase a,t_BD_MaterialSale b,t_BD_MaterialProduce c
                where a.FMATERIALID=b.FMATERIALID and a.FMATERIALID=c.FMATERIALID and  a.FMATERIALID='" + F_RDLV_Materal + "'";
                DataTable dt_mate = DBUtils.ExecuteDataSet(context, sql_mate).Tables[0];
                string baseunit = "";
                string saleunit = "";
                string pounit = "";
                if (dt_mate != null && dt_mate.Rows.Count > 0)
                {
                    baseunit = dt_mate.Rows[0]["FBaseUnitId"].ToString();
                    saleunit = dt_mate.Rows[0]["FSaleUnitId"].ToString();
                    pounit = dt_mate.Rows[0]["FProduceUnitId"].ToString();
                }



                string sql_Insert = @"/*dialect*/  insert into QLTK_t_OutboundQuantity(FID,FBILLNO,FDOCUMENTSTATUS,F_QLTK_ORGID,F_QLTK_DATE,F_QLTK_MATERIAL,F_QLTK_MOTO,F_QLTK_SALEUNIT,F_QLTK_QTY
                ,F_QLTK_INDATE,F_QLTK_BASEUNIT,F_QLTK_BASEQTY,F_QLTK_POUNIT,F_QLTK_POQTY) values('" + dt_1.Rows[0][0].ToString() + "','" + dt_1.Rows[0][0].ToString() + "','C','" + ProOrgId + "','" + RDLV_Date + "'," +
                "'" + F_RDLV_Materal + "','" + FMTONO + "','" + saleunit + "','" + SumOrderNotInQtySale + "','" + dateTime1 + "','" + baseunit + "','" + SumOrderNotInQtyBase + "','" + pounit + "','" + SumOrderNotInQtyPo + "')";
                DBUtils.Execute(context, sql_Insert);

                FID = dt_1.Rows[0][0].ToString();

            }
            return FID;

        }

        /// <summary>
        /// 插入预计出 单据体
        /// </summary>
        public void InsertOutboundQuantityEData(Context context, string Fid, string FBillNo, string FDate, decimal FQty, string FDeliveryDate, decimal OrderNotInQtyBase, decimal OrderNotInQtySale, decimal OrderNotInQtyPo, string fillName, string F_QLTK_CUST, string F_QLTK_STAFF)
        {

            string sql_Fentryid = @"/*dialect*/  insert into Z_QLTK_t_OutboundQuantityE(column1)  values(1)";
            DBUtils.Execute(context, sql_Fentryid);

            string sql = @"/*dialect*/   select Id from Z_QLTK_t_OutboundQuantityE";
            DataTable dt_2 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

            string sql_FID = @"/*dialect*/  delete from Z_QLTK_t_OutboundQuantityE";
            DBUtils.Execute(context, sql_FID);
            string sql_InsertE = @"/*dialect*/  insert into QLTK_t_OutboundQuantityE(FID,FEntryID,F_QLTK_POORDER,F_QLTK_ORDERDATE,F_QLTK_DATEE,F_QLTK_PoQtyE,F_QLTK_BASEQTYE,F_QLTK_SALEQTYE
            ,F_QLTK_PONOQTYE,F_QLTK_BILLNAME,F_QLTK_CUST,F_QLTK_STAFF) values('" + Fid + "','" + dt_2.Rows[0][0].ToString() + "','" + FBillNo + "','" + FDate + "','" + FDeliveryDate + "','" + FQty + "','" + OrderNotInQtyBase + "','" + OrderNotInQtySale + "','" + OrderNotInQtyPo + "','" + fillName + "','" + F_QLTK_CUST + "','" + F_QLTK_STAFF + "')";
            DBUtils.Execute(context, sql_InsertE);


        }

        /// <summary>
        /// 插入预计入 单据头
        /// </summary>
        public string InsertPreRecordedData(Context context, DateTime dateTime, DateTime dateTime1, string F_RDLV_Materal, string FMTONO, string ProOrgId, decimal SumOrderNotInQtyBase, decimal SumOrderNotInQtySale, decimal SumOrderNotInQtyPo)
        {

            string RDLV_Date = dateTime.ToString("yyyy-MM-dd");
            string FID = "";
            //首先判断当日是否存在单据头数据，如果存在直接插入单据体，不存在，先插入单据头
            string sql = @"/*dialect*/  select * from QLTK_t_PreRecorded where CONVERT(varchar(100), F_QLTK_DATE, 23)='" + RDLV_Date + "' and F_QLTK_Material='" + F_RDLV_Materal + "' and F_QLTK_Moto='" + FMTONO + "' and F_QLTK_OrgId='" + ProOrgId + "'";
            DataTable dt = DBUtils.ExecuteDataSet(context, sql).Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                FID = dt.Rows[0][0].ToString();

            }
            else
            {
                //插入单据头

                string sql_FID = @"/*dialect*/  insert into Z_QLTK_t_PreRecorded(column1)  values(1)";
                DBUtils.Execute(context, sql_FID);

                sql = @"/*dialect*/   select Id from Z_QLTK_t_PreRecorded";
                DataTable dt_1 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

                sql_FID = @"/*dialect*/  delete from Z_QLTK_t_PreRecorded";
                DBUtils.Execute(context, sql_FID);

                //查询计量单位
                string sql_mate = @"/*dialect*/ select FBaseUnitId,FSaleUnitId,FProduceUnitId from t_BD_MaterialBase a,t_BD_MaterialSale b,t_BD_MaterialProduce c
                where a.FMATERIALID=b.FMATERIALID and a.FMATERIALID=c.FMATERIALID and  a.FMATERIALID='" + F_RDLV_Materal + "'";
                DataTable dt_mate = DBUtils.ExecuteDataSet(context, sql_mate).Tables[0];
                string baseunit = "";
                string saleunit = "";
                string pounit = "";
                if (dt_mate != null && dt_mate.Rows.Count > 0)
                {
                    baseunit = dt_mate.Rows[0]["FBaseUnitId"].ToString();
                    saleunit = dt_mate.Rows[0]["FSaleUnitId"].ToString();
                    pounit = dt_mate.Rows[0]["FProduceUnitId"].ToString();
                }



                string sql_Insert = @"/*dialect*/  insert into QLTK_t_PreRecorded(FID,FBILLNO,FDOCUMENTSTATUS,F_QLTK_ORGID,F_QLTK_DATE,F_QLTK_MATERIAL,F_QLTK_MOTO
                ,F_QLTK_SALEUNIT,F_QLTK_QTY,F_QLTK_INDATE,F_QLTK_BASEUNIT,F_QLTK_BASEQTY,F_QLTK_POUNIT,F_QLTK_POQTY) values('" + dt_1.Rows[0][0].ToString() + "','" + dt_1.Rows[0][0].ToString() + "','C','" + ProOrgId + "','" + RDLV_Date + "'," +
                "'" + F_RDLV_Materal + "','" + FMTONO + "','" + saleunit + "','" + SumOrderNotInQtySale + "','" + dateTime1 + "','" + baseunit + "','" + SumOrderNotInQtyBase + "','" + pounit + "','" + SumOrderNotInQtyPo + "')";
                DBUtils.Execute(context, sql_Insert);

                FID = dt_1.Rows[0][0].ToString();

            }
            return FID;

        }

        /// <summary>
        /// 插入预计入 单据体
        /// </summary>
        public void InsertPreRecordedEData(Context context, string Fid, string FBillNo, string FDate, decimal FQty, string FPlanStartDate, string FPlanFinishDate, decimal OrderNotInQtyBase, decimal OrderNotInQtySale, decimal OrderNotInQtyPo)
        {

            string sql_Fentryid = @"/*dialect*/  insert into Z_QLTK_t_PreRecordedE(column1)  values(1)";
            DBUtils.Execute(context, sql_Fentryid);

            string sql = @"/*dialect*/   select Id from Z_QLTK_t_PreRecordedE";
            DataTable dt_2 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

            string sql_FID = @"/*dialect*/  delete from Z_QLTK_t_PreRecordedE";
            DBUtils.Execute(context, sql_FID);
            string sql_InsertE = @"/*dialect*/  insert into QLTK_t_PreRecordedE(FID,FEntryID,F_QLTK_POORDER,F_QLTK_ORDERDATE,F_QLTK_POQTYE,F_QLTK_STARTDATE,F_QLTK_ENDDATE
            ,F_QLTK_SALEQTYE,F_QLTK_BASEQTYE,F_QLTK_PONOQTYE) values('" + Fid + "','" + dt_2.Rows[0][0].ToString() + "','" + FBillNo + "','" + FDate + "','" + FQty + "','" + FPlanStartDate + "','" + FPlanFinishDate + "','" + OrderNotInQtySale + "','" + OrderNotInQtyBase + "','" + OrderNotInQtyPo + "')";
            DBUtils.Execute(context, sql_InsertE);


        }

        /// <summary>
        /// 插入当日可发量
        /// </summary>
        public void InsertData(Context context, DateTime dateTime, DateTime dateTime1, string F_RDLV_Materal, decimal F_RDLV_DayInQty, decimal F_RDLV_AccumulateInQty, decimal F_RDLV_OrderNotInQty, decimal F_RDLV_AvailableQty, decimal F_RDLV_UnitQty, string F_RDLV_OrgIdE, decimal F_RDLV_HideUnitQty, string FMTONO, decimal F_QLTK_Inventory, decimal F_QLTK_PreRecorded, decimal F_QLTK_OutboundQuantity, decimal F_QLTK_DailyForecast, string F_QLTK_InFID, string F_QLTK_OutFID, decimal yjkflhj)
        {

            string RDLV_Date = dateTime.ToString("yyyy-MM-dd");

            //首先判断当日是否存在单据头数据，如果存在直接插入单据体，不存在，先插入单据头
            string sql = @"/*dialect*/  select * from RDLV_t_AvailableQuantity where CONVERT(varchar(100), F_RDLV_Date, 23)='" + RDLV_Date + "' and F_RDLV_OrgId='" + F_RDLV_OrgIdE + "'";
            DataTable dt = DBUtils.ExecuteDataSet(context, sql).Tables[0];

            if (dt != null && dt.Rows.Count > 0)
            {
                //插入单据体数据
                string sql_Fentryid = @"/*dialect*/  insert into Z_RDLV_t_AvailableQuantityE(column1) values(1)";
                DBUtils.Execute(context, sql_Fentryid);

                sql = @"/*dialect*/   select Id from Z_RDLV_t_AvailableQuantityE";
                DataTable dt_2 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

                string sql_FID = @"/*dialect*/  delete from Z_RDLV_t_AvailableQuantityE";
                DBUtils.Execute(context, sql_FID);
                string sql_InsertE = @"/*dialect*/  insert into RDLV_t_AvailableQuantityE(fentryid,fid,F_RDLV_DateE,F_RDLV_Materal,F_RDLV_DayInQty,F_RDLV_AccumulateInQty,F_RDLV_OrderNotInQty,F_RDLV_AvailableQty,F_RDLV_UnitQty,F_RDLV_OrgIdE,F_RDLV_HideUnitQty,F_QLTK_Tracking,F_QLTK_Inventory,F_QLTK_PreRecorded,F_QLTK_OutboundQuantity,F_QLTK_DailyForecast,F_QLTK_InFID,F_QLTK_OutFID,F_QLTK_PreRecordedCount) values('" + dt_2.Rows[0][0].ToString() + "','" + dt.Rows[0][0].ToString() + "','" + dateTime1 + "','" + F_RDLV_Materal + "','" + F_RDLV_DayInQty + "','" + F_RDLV_AccumulateInQty + "','" + F_RDLV_OrderNotInQty + "','" + F_RDLV_AvailableQty + "','" + F_RDLV_UnitQty + "','" + F_RDLV_OrgIdE + "','" + F_RDLV_HideUnitQty + "','" + FMTONO + "','" + F_QLTK_Inventory + "','" + F_QLTK_PreRecorded + "','" + F_QLTK_OutboundQuantity + "','" + F_QLTK_DailyForecast + "','" + F_QLTK_InFID + "','" + F_QLTK_OutFID + "','" + yjkflhj + "')";
                DBUtils.Execute(context, sql_InsertE);

            }
            else
            {
                //插入单据头

                string sql_FID = @"/*dialect*/  insert into Z_RDLV_t_AvailableQuantity(column1)  values(1)";
                DBUtils.Execute(context, sql_FID);

                sql = @"/*dialect*/   select Id from Z_RDLV_t_AvailableQuantity";
                DataTable dt_1 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

                sql_FID = @"/*dialect*/  delete from Z_RDLV_t_AvailableQuantity";
                DBUtils.Execute(context, sql_FID);


                string sql_Insert = @"/*dialect*/  insert into RDLV_t_AvailableQuantity(FBILLNO,FID,FDocumentStatus,F_RDLV_Date,F_RDLV_OrgId) values('" + dt_1.Rows[0][0].ToString() + "','" + dt_1.Rows[0][0].ToString() + "','C','" + RDLV_Date + "','" + F_RDLV_OrgIdE + "')";
                DBUtils.Execute(context, sql_Insert);



                string sql_Fentryid = @"/*dialect*/  insert into Z_RDLV_t_AvailableQuantityE(column1)  values(1)";
                DBUtils.Execute(context, sql_Fentryid);

                sql = @"/*dialect*/   select Id from Z_RDLV_t_AvailableQuantityE";
                DataTable dt_2 = DBUtils.ExecuteDataSet(context, sql).Tables[0];

                sql_FID = @"/*dialect*/  delete from Z_RDLV_t_AvailableQuantityE";
                DBUtils.Execute(context, sql_FID);
                string sql_InsertE = @"/*dialect*/  insert into RDLV_t_AvailableQuantityE(fentryid,fid,F_RDLV_DateE,F_RDLV_Materal,F_RDLV_DayInQty,F_RDLV_AccumulateInQty,F_RDLV_OrderNotInQty,F_RDLV_AvailableQty,F_RDLV_UnitQty,F_RDLV_OrgIdE,F_RDLV_HideUnitQty,F_QLTK_Tracking,F_QLTK_Inventory,F_QLTK_PreRecorded,F_QLTK_OutboundQuantity,F_QLTK_DailyForecast,F_QLTK_InFID,F_QLTK_OutFID,F_QLTK_PreRecordedCount) values('" + dt_2.Rows[0][0].ToString() + "','" + dt_1.Rows[0][0].ToString() + "','" + dateTime1 + "','" + F_RDLV_Materal + "','" + F_RDLV_DayInQty + "','" + F_RDLV_AccumulateInQty + "','" + F_RDLV_OrderNotInQty + "','" + F_RDLV_AvailableQty + "','" + F_RDLV_UnitQty + "','" + F_RDLV_OrgIdE + "','" + F_RDLV_HideUnitQty + "','" + FMTONO + "','" + F_QLTK_Inventory + "','" + F_QLTK_PreRecorded + "','" + F_QLTK_OutboundQuantity + "','" + F_QLTK_DailyForecast + "','" + F_QLTK_InFID + "','" + F_QLTK_OutFID + "','" + yjkflhj + "')";
                DBUtils.Execute(context, sql_InsertE);


                //插入单据体
            }

        }


        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(Context ctx, string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(ctx, Sql).Tables[0];
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }
        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }

        /// <summary>
        /// 销售订单主报文
        /// </summary>
        public class mainTableList
        {
            public string ddbh { get; set; }//订单编号           
        }
        /// <summary>
        /// 销售订单明细报文
        /// </summary>
        public class detailList
        {
            public operate operate { get; set; }
            public dataList data { get; set; }

        }


        public class operate
        {
            public string action { get; set; }
            public string actionDescribe = "";
        }
        /// <summary>
        /// 销售订单明细数据报文
        /// </summary>
        public class dataList
        {
            public string erpyjfhrq { get; set; }//ERP预计发货日期
            public string id { get; set; }//CRM明细内码

        }
        /// <summary>
        /// CRM更新销售订单接口
        /// </summary>
        public Return CRMUpdateSalesOrder(Context context, mainTableList mainTable, List<detailList> detail1)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_order_delivery_date";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting(context, "更新销售订单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1);


            return result;
        }

        /**
        * 接口返回值自定义 
        */
        public class Return
        {
            public string status { get; set; }
            public string datajson { get; set; }
        }
        /// <summary>
        /// CRM更新销售订单OST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, mainTableList mainTable, List<detailList> detail1)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\"CRM\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }

    }
}
